class BaseEditWithTree {
    constructor(getTreeUrl, changeCatalogueUrl, fetchNodeUrl, saveNodeUrl, deleteNodeUrl, returnUrl) {
        this.getTreeUrl = getTreeUrl;
        this.changeCatalogueUrl = changeCatalogueUrl;
        this.fetchNodeUrl = fetchNodeUrl;
        this.saveNodeUrl = saveNodeUrl;
        this.deleteNodeUrl = deleteNodeUrl;
        this.returnUrl = returnUrl;
        this.pageStatus = 0;
    }
    // 初始化页面,得到树形节点数据
    OnPageLoad() {
        // 用于判断表单是否有更改
        $("#form_data :input").change(function () {
            $("#form_data").data("changed", true);
        });
        $("#search_btn").hide();                  // 无需搜索，隐藏搜索按钮
        $("#form_data").data("changed", false);   // 初始化form数据提交状态

        this.InitTreeObject();
    }
    DoBack() {
        location.assign(parent.basePath + this.returnUrl);
    }
    InitTreeObject() {
        // 初始化树形控件
        $('#treeContent').jstree({
            "core": {
                "animation": 200,
                "multiple": false,
                "check_callback": true,
                "themes": {
                    "responsive": true,
                    "dots": false,
                    "icons": true
                },
                "data": {
                    'dataType': 'JSON',
                    'contentType': 'application/json; charset=utf-8',
                    'type': 'GET',
                    'url': parent.basePath + this.getTreeUrl,
                    'data': (node) => {
                        let _nodeId = node.id === '#' ? -1 : (node.id === 'j1_1' ? 0 : node.id);
                        return {'parentKey': _nodeId, 'isPopupWnd': 0, 'isAdministrator': 1};
                    },
                    'complete': () => {
                        $("#loading").hide();
                    }
                }
            },
            "types": {
                "#": {"max_depth": -1, "max_children": -1, "valid_children": ["root"]},
                "root": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/root.png", "valid_children": -1},
                "default": {"max_depth": -1, "max_children": -1, "valid_children": -1},
                "leaf": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/folder_close.png", "valid_children": -1},
                "trash": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/trash.png", "valid_children": -1}
            },
            "plugins": ["dnd", "contextmenu", "types", "wholerow"],
            "dnd": {
                "copy": false
            },
            "contextmenu": {
                "items": {
                    "create": {
                        "label": "新建目录",
                        "icon": parent.basePath + "/images/tree/add.png",
                        "action": (data) => {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            this.InsertNode();
                        }
                    },
                    "edit": {
                        "label": "编辑目录",
                        "icon": parent.basePath + "/images/tree/edit.png",
                        "action": (data) => {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                        },
                        "separator_after": true
                    },
                    "remove": {
                        "label": "删除目录",
                        "icon": parent.basePath + "/images/tree/delete.png",
                        "action": (data) => {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            this.DeleteNode();
                        }
                    }
                }
            }
        });
        $('#treeContent').on('select_node.jstree', (event, data) => {
            // 清除错误状态
            this.ClearForm();

            let _selectedNodeId = data.node.id;
            let _select_node = $("#" + _selectedNodeId);

            if (_selectedNodeId !== "j1_1") {
                $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：编辑");
                this.pageStatus = 0; // 设置编辑状态
                let ref = $.jstree.reference('treeContent');
                let _parentId = ref.get_parent(_select_node);
                let _parent_node = $("#" + _parentId);
                $('#ParentCatalogueName').val(_parent_node.attr("fullname"));

                // 重新设置选择的结点ID
                _selectedNodeId = _selectedNodeId === "j1_1" ? 0 : _selectedNodeId;
                $('#CatalogueId').val(_selectedNodeId);
                // 如果不是客户节点，则取得相应的目录
                this.FetchByKey(_selectedNodeId);
            } else {
                // 如果是客户节点，清空右边表单内容，准备下一个记录
                $("#OperateMode").html("");
                $('#ParentCatalogueName').val("");
                this.pageStatus = -1; // 设置为无效状态
            }
        });
        // 节点展开后，重新设置图标
        $('#treeContent').on('open_node.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1") {
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_open.png");
                } else {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/trash_o.png");
                }
            }
        });
        // 节点收回后，重新设置图标
        $('#treeContent').on('close_node.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1") {
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_close.png");
                } else {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/trash.png");
                }
            }
        });
        // 删除节点后，设置父节点图标
        $('#treeContent').on('delete_node.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelectedParent = data.parent;
            let _nodeOfSelectedParent = $("#" + _nodeIdOfSelectedParent);
            if (_nodeIdOfSelectedParent !== "j1_1") {
                if (ref.is_leaf(_nodeOfSelectedParent) === true) {
                    ref.set_icon(_nodeOfSelectedParent, parent.basePath + "/images/tree/folder_close.png");
                }
            }
        });
        // 树形结点打开后
        $('#treeContent').on('after_open.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            // 选择该结点
            let _newNode = $("#" + $("#CatalogueId").val());
            if (_newNode.length > 0) {
                ref.select_node(_newNode);
            }
        });
        // 所有节点完成装载，只运行一次
        $('#treeContent').on('ready.jstree', () => {
            let ref = $.jstree.reference('treeContent');
            let _obj = $("#j1_1");
            ref.open_node(_obj);     // 打开当前第一层节点
            ref.select_node(_obj);
        });
        // 拖动节点结束后的事件
        $('#treeContent').on('move_node.jstree', (event, data) => {
            if (data.old_parent !== data.parent) {
                let _parentId = data.parent === "j1_1" ? 0 : data.parent;
                let params = {};
                params['CatalogueId'] = parseInt(data.node.id);   // 选择的节点
                params['ParentId'] = parseInt(_parentId);         // 目标节点

                $.ajax({
                    type: "POST",
                    url: parent.basePath + this.changeCatalogueUrl,
                    timeout: 30 * 1000,
                    data: JSON.stringify(params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: () => {
                    }
                }).done((data) => {
                    if (parseInt(data) > 0) {
                        ShowSuccessMessagePanel("所属目录改变成功。");
                    }
                }).fail((data) => {
                    ajaxError(data, 1);
                }).always(() => {
                });
            }
        });
    }
    // 创建新结点
    NewNode() {
        let node = {};
        let li_attr = {};
        node['id'] = $("#CatalogueId").val().toString();
        node['text'] = $.trim($("#CatalogueName").val().toString());
        node['type'] = "leaf";
        node['children'] = false;
        li_attr['fullname'] = $.trim($("#ParentCatalogueName").text()) + " → " + $.trim($("#CatalogueName").val());
        node['li_attr'] = li_attr;
        return node;
    }
    FetchByKey(nodeId) {
        $.ajax({
            type: "GET",
            url: parent.basePath + this.fetchNodeUrl,
            timeout: 30 * 1000,
            data: {'key': nodeId},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done((data) => {
            $("#CatalogueId").val(data.catalogueId);             // 目录ID
            $("#ParentId").val(data.parentId);                   // 目录ID
            $("#ParentCatalogueName").val(data.parentName);      // 所属目录
            $("#OrderNo").val(data.orderNo);                     // 目录编码
            $("#CatalogueName").val(data.catalogueName);         // 目录
            $("#Description").val(data.description);             // 备注
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(( ) => {
            $("#loading").hide();
        });
    }
    // 得到目录数据
    GetNodeData() {
        let item = {};
        item['catalogueId'] = $("#CatalogueId").val();
        item['parentId'] = $("#ParentId").val();
        item['orderNo'] = $.trim($("#OrderNo").val());
        item['catalogueName'] = $.trim($("#CatalogueName").val());
        item['description'] = formatNullInputValue($.trim($("#Description").val()));
        item['updatedBy'] = $("#UserId").val();

        return JSON.stringify(item);
    }
    // 新增信息
    InsertNode() {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择一个所属目录。");
            return;
        }
        this.pageStatus = 1; // 设置为新增状态

        // 清空表单内容，准备下一个记录
        this.ClearForm();
        $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：增加");
        let _selectedNodeId = sel === "j1_1" ? 0 : sel;
        let _select_node = $("#" + sel);
        $('#ParentCatalogueName').val(_select_node.attr("fullname"));
        $('#ParentId').val(_selectedNodeId);
        $('#CatalogueId').val("0");

        // 设置焦点
        $("#OrderNo").focus();
    }
    // 保存数据
    SaveNode() {
        // 设置为无效状态
        if (parseInt(this.pageStatus) === -1) {
            ShowErrorMessagePanel("对不起，不能修改系统初始信息。");
            return false;
        }
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        let _obj = $("#" + sel);
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择目录。");
            return false;
        }

        if (!$("#form_data").valid())
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + this.saveNodeUrl,
            timeout: 30 * 1000,
            data: this.GetNodeData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done((data) => {
            if (parseInt(data) > 0) {
                switch (parseInt(this.pageStatus)) {
                    case 0: //  编辑
                        // 修改路径名
                        let _fullname = $.trim($("#ParentCatalogueName").val()) + " → " + $.trim($("#CatalogueName").val());
                        _obj.attr("fullname", _fullname);
                        ref.rename_node(_obj, $.trim($("#CatalogueName").val())); // 修改节点文字
                        break;
                    case 1: // 新增
                        $("#CatalogueId").val(data);
                        //let _obj = $("#" + sel);
                        // 增加树形节点
                        ref.create_node(_obj, this.NewNode());
                        ref.load_node(_obj);
                        ref.open_node(_obj);
                        // 取消当前选择点
                        ref.deselect_node(_obj);
                        // 选择该结点
                        let _newNode = $("#" + data);
                        ref.select_node(_newNode);
                        this.pageSstatus = 0; // 设置为编辑状态
                        break;
                }
                ShowSuccessMessagePanel('保存成功。');
            }
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    // 删除
    DeleteNode() {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择目录。");
            return false;
        }
        if (sel === "j1_1") {
            ShowErrorMessagePanel("不能删除根节点。");
            return false;
        }
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', () => {
            let instance = {};
            instance['catalogueId'] = $("#CatalogueId").val();
            instance['deletedBy'] = $("#UserId").val();
            $.ajax({
                type: "POST",
                url: parent.basePath + this.deleteNodeUrl,
                timeout: 30 * 1000,
                data: JSON.stringify(instance),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: () => {
                }
            }).done((data) => {
                if (data > 0) {
                    // 删除树形节点
                    let sel = $.jstree.reference('treeContent').get_selected()[0];
                    $.jstree.reference('treeContent').delete_node(sel);

                    // 删除成功后，清空右侧表单内容
                    this.ClearForm();
                    $("#OperatingMode").html("");
                    $('#ParentCatalogueName').val("");

                    $('#CatalogueId').val("0");
                    ShowSuccessMessagePanel("删除成功。");
                }
            }).fail((data) => {
                ajaxError(data, 1);
            }).always(( ) => {
            });
        });
    }
    ClearForm() {
        // 清空表单内容，准备下一个记录
        $(':input', '#form_data').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $('#form_data')[0].reset();
        $(".error").removeClass("error");
        $(".tooltip").remove();
        $("i[generated='true']").remove();         // 删除错误图标

        $("#OrderNo").focus();
    }
}
